package educrypt.filter;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import educrypt.commons.Alphabet;
import educrypt.commons.Text;

public class Filter {

	public static Text filterText(Text text, Alphabet knownSymbols,
			Equivalences equivalences) {
		StringBuffer filteredTextContent = new StringBuffer(text.size());
		for (char symbol : text) {
			// Do the symbol belong to the alphabet?
			boolean isKnownSymbol = knownSymbols.containsSymbol(symbol);
			if (!isKnownSymbol) {
				char equivalent = equivalences.getEquivalentSymbol(symbol);
				// Do the equivalent symbol belong to the alphabet?
				isKnownSymbol = knownSymbols.containsSymbol(equivalent);
				if (isKnownSymbol) {
					if (Character.isUpperCase(symbol)) {
						equivalent = Character.toUpperCase(equivalent);
					} else {
						equivalent = Character.toLowerCase(equivalent);
					}
					filteredTextContent.append(equivalent);
				} else {
					filteredTextContent.append(symbol);
				}
			} else {
				filteredTextContent.append(symbol);
			}
		}
		return new Text(text.getName(), text.getType(), text.getLanguage(),
				filteredTextContent.toString());
	}

	public static List<Character> getTextUnknownSymbols(Text text,
			Alphabet knownSymbols) {
		SortedSet<Character> unknownSymbolsNotRepeated = new TreeSet<Character>();
		for (char symbol : text) {
			char symbolLowerCase = Character.toLowerCase(symbol);
			if (!knownSymbols.containsSymbol(symbolLowerCase)) {
				unknownSymbolsNotRepeated.add(symbolLowerCase);
			}
		}
		List<Character> unknownSymbols = new ArrayList<Character>(
				unknownSymbolsNotRepeated);
		return unknownSymbols;
	}
}
